package portal.action.rest;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import beans.FullJobState;
import beans.HttpResultList;
import beans.RunningTask;
import dao.JobDao;
import engine.BIEngine0_1.AlgorithmOperator;
import engine.BIEngine0_1.AlgorithmThread;
import net.QueryThread;
import net.sf.json.JSONObject;
import portal.engine.JobOperator;
import portal.mybatis.dao.JobEntity;
import portal.mybatis.dao.SockectLog;
import portal.mybatis.dao.mapper.JobEntityMapper;
import portal.mybatis.dao.mapper.SockectLogMapper;
import portal.mybatis.dao.service.JobDetailService;
import portal.mybatis.dao.service.SockectLogService;

@RestController
public class JobCallBack2 {
	@Autowired
	JobDetailService jobDetailService;
	@Autowired 
	SockectLogService sockectLogService;
	@RequestMapping(value="/ws/task/callback2",method =RequestMethod.POST)
	public JSONObject callBack(String taskHash,String algHash,String status,String jobId){
		JSONObject ret=new JSONObject();
		if(jobId==null){
			ret.put("result", "success");
			ret.put("message", "无效的JobId");
			return ret;
		}
		JobEntity jb=jobDetailService.selectJobById(jobId);
		ret.put("result", "success");
		if(jb!=null ){//找到对应Job
			//找到对应作业，则需要更新日志信息到数据库			
			updateSocketLog(jobId);
			ret.put("message", "更新JobSockectLog");
			//response.getWriter().println(resultJson.toString());
			//new JobThread(taskId,jobId,algorithmId).start();
		}else{//未在数据库中找到对应的Job
			ret.put("message", "");
			queryAndupdateJobState(jobId,status,taskHash,algHash);
			//new QueryThread(taskId,jobId,algorithmId).start();
		}
		return ret;
	}
	/*****/
	private void updateSocketLog(String jobId){
		//根据jobId 获取logUrl
		String fileUrl =JobOperator.queryLogFileUrl(jobId);
		if(fileUrl!=null){
			//根据url下载log 文件并返回文件地址
			String filePath=JobOperator.downloadLogFile(fileUrl,jobId);
			if(filePath==null)//
				return;
			//准备待更新的数据
			SockectLog slog=new SockectLog();
			slog.setJobId(jobId);
			slog.setLogFileUri(filePath);
			//更新到数据库
			sockectLogService.updateByKeySelective(slog);
		}
	}
	private void queryAndupdateJobState(String jobId,String status,String taskHash,String algHash){		
		updateJobFullState(jobId,status,taskHash,algHash);
		//获取sockectLog 中的 ,若为进行中需要获取他的日志文件及状态，并更新
		SockectLog key =new SockectLog();
		key.setJobId(jobId);
		SockectLog s=sockectLogService.selectByKey(key) ;
		if(s!=null && "2".equals(s.getAlgorithmState())){
			String fileUrl =JobOperator.queryLogFileUrl(jobId);
			if(fileUrl!=null){
				String filePath=JobOperator.downloadLogFile(fileUrl,jobId);
				SockectLog slog=new SockectLog();
				slog.setJobId(jobId);
				slog.setLogFileUri(filePath);
				slog.setAlgorithmState("1");
				sockectLogService.updateByKeySelective(slog);
			}
		}
	}
	/********
	 * 更新指定jobId 的state
	 * 从工作流中获取该jobId 的state 信息。若状态为 DONE 或者 EXIT 则更新history_job中的 end_time,isNew,isSuccess,name,full_info 
	 * 更新成功则更新histroy_algorith 中的end_time ,并返回true,
	 * 否则返回false
	 * **********/
	private boolean updateJobFullState(String jobId,String status,String taskHash,String algHash){
		if("DONE".equals(status)|| "EXIT".equals(status)){
			//1、更新History_job 中的信息
			AlgorithmThread algorithmThread = RunningTask.TASKMAP.getTask(taskHash).runningTaskBean.runningAlgorithms.get(algHash);
			if(null!=algorithmThread)
				algorithmThread.updateJobFullState(jobId, 30);
			//algorithmState = socketLogDao.queryAlgorithmStateByJobId(jobId);
			//2、第一步若操作成功则更新histroy_algorith中信息
			return true;
		}
		return false;
		
		
	}
	/*public boolean updateJobFullState1(String jobId, int times ,String algHash ,String taskHash){
		HttpResultList result = null;
		try {
			result = AlgorithmOperator.getJobFullState(jobId, AlgorithmOperator.getToken(null, null).getMessage());
		} catch (IOException e) {
			e.printStackTrace();
		}
		FullJobState fullJobState = (FullJobState)result.getDatas().get(0);
		if(fullJobState.getStatus().equals("DONE")||fullJobState.getStatus().equals("EXIT")){
			JobDao jobDao = new JobDao();
			if(jobDao.updateJobState(fullJobState.getStatus(),
					fullJobState.getJobName(),
					JSONObject.fromObject(fullJobState).toString(),
					taskHash,
					algHash,
					jobId)){
				//1、当前jobID及job status 到jobState Map 中
				//2、保存fullJobState到算法线程jobState列表中
				//this.checkJobState(fullJobState);
				AlgorithmThread algorithmThread = RunningTask.TASKMAP.getTask(taskHash).runningTaskBean.runningAlgorithms.get(algHash);
				algorithmThread.checkJobState(fullJobState);
				return true;
			}else{
				return false;
			}
		}//else{
		return false;
		//}
	}*/
	
}
